package com.atguigu.gulimallcart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimallcart.feign.ProductFeignService;
import com.atguigu.gulimallcart.interceptor.CartInterceptor;
import com.atguigu.gulimallcart.service.CartService;
import com.atguigu.gulimallcart.vo.Cart;
import com.atguigu.gulimallcart.vo.CartItem;
import com.atguigu.gulimallcart.vo.SkuInfoVo;
import com.atguigu.gulimallcart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author houChen
 * @date 2022/1/5 12:48
 * @Description:
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    private final String CART_PREFIX = "gulimall:cart:";

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * @Description:  获取到我们要操作的购物车:  临时购物车   用户登录过的购物车
     * @param
     * @author  houChen
     * @date  2022/1/6 22:17
     */
    private BoundHashOperations<String, Object, Object>  getCartOps() {
        //1、获取当前的用户信息
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfo.getUserId() != null) {  //说明用户是处于登录状态的
            cartKey = CART_PREFIX + userInfo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> options = redisTemplate.boundHashOps(cartKey);
        return options;
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isBlank(res)){
            CartItem cartItem = new CartItem();
            //说明购物车无此商品
            //1、远程查询，当前添加的商品的详细信息
            CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo sku = skuInfo.getData("skuInfo",new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setCheck(false);
                cartItem.setCount(num);
                cartItem.setImg(sku.getSkuDefaultImg());
                cartItem.setPrice(sku.getPrice());
                cartItem.setTitle(sku.getSkuTitle());
            }, executor);

            //2、远程查询sku的组合信息
            CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(()->{
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            //3、商品添加到购物车
            CompletableFuture.allOf(completableFuture1,completableFuture2).get(); //等两个异步任务都完成
            String cartItemStr = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemStr);
            return cartItem;
        }else{
            //购物车中有此商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();
        if (userInfo.getUserId()!=null){
            //登录
            //如果临时购物车的数据还没有进行合并
            List<CartItem> tempCartItem = getCartItems(CART_PREFIX + userInfo.getUserKey());
            if(tempCartItem!=null){
                //临时购物车有数据，需要合并,将临时购物车中的内容添加到实际购物车中
                for (CartItem item : tempCartItem) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //合并后，清空临时购物车
                clearCart(CART_PREFIX + userInfo.getUserKey());
            }
            //获取登录后的购物车
            List<CartItem> cartItem = getCartItems(CART_PREFIX + userInfo.getUserId());
            cart.setItems(cartItem);
        }else{
            //没登录
            String cartKey = CART_PREFIX + userInfo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> cartItem = getCartItems(cartKey);
            cart.setItems(cartItem);
        }
        return cart;
    }


    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> options = redisTemplate.boundHashOps(cartKey);
        List<Object> values = options.values();
        if(values!=null && values.size()>0){
            List<CartItem> collect = values.stream().map(item -> {
                String s = (String)item;
                CartItem cartItem = JSONObject.parseObject(s, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * @Description:  清空指定的购物车
     * @param cartKey
     * @author  houChen
     * @date  2022/1/9 23:38
     */
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }



    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else{
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            List<CartItem> collect = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item -> {
                        //将购物车中的商品更新为最新价格
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    })
                    .collect(Collectors.toList());
            return collect;
        }
    }
}